// 导入compression-webpack-plugin
// 定义多页面配置
const Setting = require('./setting.env')
const path = require("path");
const spritesList = require("./build/sprite"); //精灵图插件函数
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const resolve = (dir) => {
  return path.join(__dirname, dir);
};
module.exports = {
  publicPath: Setting.publicPath,
  assetsDir: Setting.assetsDir,
  outputDir: Setting.outputDir,
  lintOnSave: Setting.lintOnSave,
  productionSourceMap: Setting.productionSourceMap,
  css: {
    // 使用 css 分离插件 mini-css-extract-plugin，不然骨架屏组件里的 <style> 不起作用，
    extract: true,
    loaderOptions: {
      // 全局引入less
      less: {
        globalVars: {
          hack: `true; @import '~@/assets/css/common.less';@import '~@/assets/css/test.less'`,
        },
        modifyVars: {
          // 或者可以通过 less 文件覆盖（文件路径为绝对路径）
          hack: `true; @import '~@/assets/css/theme.less';`
        },
      },
    },
  },
  /**
   * [chainWebpack 是一个函数，会接收一个基于 webpack-chain 的 ChainableConfig 实例。允许对内部的 webpack 配置进行更细粒度的修改。]
   * @param  {[type]} config [description]
   * @return {[type]}        [description]
   */
  chainWebpack: (config) => {
    config.plugins.delete("preload") // 移除预加载减少手机用户流量的使用
    config.plugins.delete("prefetch")
    // 移除pwa
    if(!Setting.pwa) {
      config.plugins.delete('pwa');
    }
    config.plugin("html").tap((args) => {
      let cdnList = []
      let cssList = []
      // cdn和埋点地址
      cdnList.push((process.env && process.env.VUE_APP_VUE_URL) || Setting.publicPath + "cdn/vue.min.js")
      cdnList.push((process.env && process.env.VUE_APP_VUEX_URL) || Setting.publicPath + "cdn/vuex.min.js")
      cdnList.push( (process.env && process.env.VUE_APP_VUE_ROUTER_URL) || Setting.publicPath + "cdn/vue-router.min.js")
      cdnList.push((process.env && process.env.VUE_APP_AXIOS_URL) || Setting.publicPath + "cdn/axios.min.js")
      // args[0].vue =
      //   (process.env && process.env.VUE_APP_VUE_URL) || "./cdn/vue.min.js"
      // args[0].vuex =
      //   (process.env && process.env.VUE_APP_VUEX_URL) || "./cdn/vuex.min.js"
      // args[0].vueRouter =
      //   (process.env && process.env.VUE_APP_VUE_ROUTER_URL) || "./cdn/vue-router.min.js"
      // args[0].axios =
      //   (process.env && process.env.VUE_APP_AXIOS_URL) || "./cdn/axios.min.js"
      args[0].cdnList = cdnList
      args[0].cssList = cssList
      return args;
    });
    config.resolve.alias
      .set("@", resolve("src")) // key,value自行定义，比如.set('@@', resolve('src/components'))
      .set("@components", resolve("src/components"))
      .set("@images", resolve("src/assets/images"))
      .set("@fonts", resolve("src/assets/fonts"))
      .set("@css", resolve("src/assets/css"))
      .set("@api", resolve("src/api"))
      .set("@utils", resolve("src/libs/utils"))
    if (process.env.NODE_ENV === "production") {
      if (process.env.VUE_APP_CURRENTMODE === "analyz") {
        config
          .plugin("webpack-bundle-analyzer")
          .use(require("webpack-bundle-analyzer").BundleAnalyzerPlugin)
          .end();
      }
    }
  },
  /**
   * [configureWebpack 提供一个对象，该对象将会被 webpack-merge 合并入最终的 webpack 配置（以函数方式配置或者以插件方式配置webpack）]
   * @param  {[type]} config [description]
   * @return {[type]}        [description]
   */
  configureWebpack: (config) => {
    const plugins = config.plugins
    // 配置cdn
    config.externals = {
      // vant使用页面内按需引入，不做配置
      vue: "Vue",
      "vue-router": "VueRouter",
      vuex: "Vuex",
      axios: "axios",
    };
    if (spritesList.length > 0) {
      plugins.push(...spritesList)
    }
    Object.assign(config.optimization.splitChunks.cacheGroups, {
            'i18n': { // 分离组件库，可拆分echarts等大型包文件
                name: 'i18n', // name 为true会自动命名
                test: /vue-i18n/,
                priority: 10,
                chunks: 'initial' // initial入口引入 all全部 anync异步引入
            },
            'lazyload': { // 分离组件库，可拆分echarts等大型包文件
                name: 'lazyload', // name 为true会自动命名
                test: /vue-lazyload/,
                priority: 10,
                chunks: 'initial' // initial入口引入 all全部 anync异步引入
            },
            // jQuery: { // 
            //     name: 'jQuery',
            //     test: /[\\/]jquery[\\/]/,
            //     priority: 6,
            //     chunks: 'all'
            // },
    })
    // 骨架屏插件，建议放一张轻量的base64图，或者尽量精简的页面
    plugins.push(new SkeletonWebpackPlugin({
      webpackConfig: {
       entry: {
        app: path.join(__dirname, './src/entry-skeleton.js')
       }
      },
      // SPA 下是压缩注入 HTML 的 JS 代码
      minimize: true,
      // 服务端渲染时是否需要输出信息到控制台
      quiet: true,
      // 根据路由显示骨架屏
      router: {
        mode: 'history',
        routes: [
        //  {
        //   path: '/',
        //   skeletonId: 'skeleton-home'
        //  },
         {
          path: '/skeleton',
          skeletonId: 'skeleton-about'
         }
        ]
      },
     }))
    if (process.env.NODE_ENV === "production") {
      // 生产环境
      plugins.push(
        new CompressionWebpackPlugin({
          algorithm: "gzip",
          test: /\.(js|css|html|ico|svg|png|jpeg|gif|less)$/i,
          threshold: 10240, // 对超过10k的数据进行压缩
          deleteOriginalAssets: false, // 是否删除原文件
        })
      );
      config.optimization.minimizer.map((arg) => {
        const option = arg.options.terserOptions.compress;
        option.drop_console = true; // 打开开关
        option.drop_debugger = true; // 打开开关
        return arg;
      })
    }
    if (process.env.VUE_APP_CURRENTMODE === "analyze") {
      plugins.push(new BundleAnalyzerPlugin());
    }
    
  },
  // {
  //   "name": "我的博客",
  //   "short_name": "博客",
  //   "icons": [
  //     {
  //       "src": "./images/commom/logo_144x144.png",
  //       "sizes": "144x144",
  //       "type": "image/png"
  //     }
  //   ],
  //   "start_url": "/index.html",
  //   "display": "standalone",
  //   "background_color": "#000000",
  //   "theme_color": "#4DBA87"
  // }
  pwa: {
    name: 'vue-mobile',
    themeColor: '#4DBA87',
    msTileColor: '#000000',
    appleMobileWebAppCapable: 'yes',
    appleMobileWebAppStatusBarStyle: 'black',
    manifestOptions: {
      "start_url": "/index.html",
      // icons直接修改public文件夹里面的icons图片即可
      // icons: [ 
      //   {
      //     src: '/favicon/favicon-32x32.png',
      //     sizes: '32x32',
      //     type: './src/assets/images/sprite/test.png'
      //   },
      //   {
      //     src: '/favicon/favicon-16x16.png',
      //     sizes: '16x16',
      //     type: 'image/png'
      //   },
      //   {
      //     src: '/favicon/apple-touch-icon-152x152.png',
      //     sizes: '152x152',
      //     type: 'image/png'
      //   },
      //   {
      //     src: '/favicon/safari-pinned-tab.svg',
      //     sizes: '942x942',
      //     type: 'image/svg+xml'
      //   },
      //   {
      //     src: '/favicon/msapplication-icon-144x144.png',
      //     sizes: '144x144',
      //     type: 'image/png'
      //   },
      // ]
    },
    // configure the workbox plugin (GenerateSW or InjectManifest)
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
      // swSrc is required in InjectManifest mode.
      swSrc: './src/service-worker.js',
      // importWorkboxFrom: 'local', // 不采用谷歌cdn方式，避免国内网络问题
      // importWorkboxFrom: 'disabled',
      // importScripts: 'https://cdn.bootcdn.net/ajax/libs/workbox-sw/6.0.0-alpha.3/workbox-sw.js'
      // ...other Workbox options...
    }
  },
  // 配置开发环境代理
  devServer: {
    // https: true, // 是否开启https
    hot: true,
    // host: '0.0.0.0',设置本机ip外部访问
    proxy:
      process.env.VUE_APP_CURRENTMODE === "test"
        ? {
            "/api": {
              target: process.env.VUE_APP_PROXYURL, // 请求源地址
              ws: true, // 是否代理ws
              changeOrigin: true, // 是否跨域
              pathRewrite: {
                "^/api": "",
              },
            },
          }
        : null,
    // before: (app) => {
    //   // 生成快速导航(也可写mock接口)
    //   app.get("/", (req, res, next) => {
    //     for (const i in pages) {
    //       res.write(`<a target="_self" href="/${i}">/${i}</a></br>`);
    //     }
    //     res.end();
    //   });
    // },
  },
};
